<template>
  <div class="food-content-box restaurant-list-box">
    <el-breadcrumb separator="/" class="page-title">
      <el-breadcrumb-item :to="{ path: 'routeSchedule' }">Route schedule</el-breadcrumb-item>
      <el-breadcrumb-item>new</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container-padding">
      <el-form :inline="true" label-position="top" :model="submitForm" size="mini" ref="submitForm" :rules="rules" v-loading="loading" class="form-min-width">
        <div class="container-box label-style">
          <el-row :gutter="20">
            <el-col>
              <el-form-item :label="$t('m.Status')" prop="status">
                <el-select  style="width: 200px" v-model="submitForm.status" placeholder="">
                  <el-option v-for="rg in status" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
                </el-select>
              </el-form-item>
              <!--<el-form-item label="Direction name en">-->
                <!--<el-select @change="initSchedule" style="width: 200px" v-model="submitForm.directionId" placeholder="">-->
                  <!--<el-option v-for="rg in directionNameEns" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>-->
                <!--</el-select>-->
              <!--</el-form-item>-->
              <el-form-item label="Route name_en" style="width: 200px">
                <el-select  style="width: 200px" v-model="submitForm.routeId" placeholder="">
                  <el-option v-for="rg in routes" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="Schedule" style="width: 200px"  prop="schedule">
                <!--<el-input v-model="submitForm.schedule"></el-input>-->
                <el-time-picker
                  v-model="submitForm.schedule"
                  format="HH:mm"
                  value-format="HH:mm:ss"
                  placeholder="">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col>
              <el-button @click.native="cancelPutForm()" size="small" style="min-width: 85px;">
                {{$t('m.Cancel')}}
              </el-button>
              <el-button @click.native="uploadSubmitForm('submitForm')"
                         v-loading.fullscreen.lock="fullscreenLoading" size="small" style="min-width: 85px;" type="warning">
                {{$t('m.Save')}}
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
  import Qs from 'qs'
  import { uploadNewRouteScheduleFormInfo, initRouteSchedule, initRouteScheduleList, onTrainDirectionQueryJson } from '../../../api/mgc_api'
  export default {
    name: 'NewRouteSchedule',
    data () {
      return {
        status: [
          {"value": 1, "text": "Active"},
          {"value": 0, "text": "Delete"},
          // {"value": 2, "text": "Suspended"},
        ],
        directionNameEns: [],
        routes: [],
        submitForm: {
          // 表单数据必填字段
          status: 1,
          routeId: null,
          schedule: null,
          directionId: null,
        },
        // 添加表单修改数据和字段
        id: '',
        fullscreenLoading: false,
        loading: false,
        rules: {
          status: [
            {required: true, message: 'please select', trigger: 'change'}
          ],
          routeId: [
            {required: true, message: 'please select', trigger: 'change'}
          ],
          schedule: [
            {required: true, message: 'please enter', trigger: 'blur'}
          ],
        }
      }
    },
    methods: {
      // message alert 用于前端错误提示信息
      messageToastErr (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: 'error'
        })
      },
      messageToastSuccess (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: 'success'
        })
      },
      cancelPutForm () {
        // if (this.id) {
        //   this.initForm()
        // } else {
        //   this.removeAgentForm ('submitForm')
        // }
        this.$router.go(-1)
      },
      // 表单信息上传
      uploadSubmitForm (submitForm) {
        this.$refs[submitForm].validate((valid) => {
          if (valid){
            console.log(valid)
            // 有id -- 则提交编辑信息
            if (this.id) {
              let formAjaxData = {
                /* 编辑时添加的字段 start */
                id: this.id,
                /* 编辑时添加的字段 end */
                status: this.submitForm.status,
                routeId: this.submitForm.routeId,
                schedule: this.submitForm.schedule,
              }
              let params = Qs.stringify(formAjaxData)
              console.log(params, 'params')
              let config = {
                'Content-Type': 'multipart/form-data'
              }
              this.fullscreenLoading = true
              uploadNewRouteScheduleFormInfo(params, config)
                .then((res) => {
                  if (res) {
                    if (res.data) {
                      console.log(res)
                      if (res.data.errorID == 0) {
                        this.messageToastSuccess('success')
                        this.initForm()
                        this.$router.push('/routeSchedule')
                        this.fullscreenLoading = false
                      }
                    } else {
                      this.messageToastErr(res.data.message)
                    }
                  }
                })
                .catch((error) => {
                  console.log(error)
                  this.fullscreenLoading = false
                  this.messageToastErr('error,please try again leter')
                })
            } else {
              //新增 -- 表单信息
              let formAjaxData = {
                status: this.submitForm.status,
                routeId: this.submitForm.routeId,
                schedule: this.submitForm.schedule,
              }
              let params = Qs.stringify(formAjaxData)
              let config = {
                'Content-Type': 'multipart/form-data'
              }
              this.fullscreenLoading = true
              uploadNewRouteScheduleFormInfo(params, config)
                .then((res) => {
                  if (res) {
                    if (res.data) {
                      console.log(res)
                      if (res.data) {
                        console.log(res)
                        if (res.data.errorID == 0) {
                          this.messageToastSuccess('success')
                          this.$refs[submitForm].resetFields()
                          this.$router.push('/routeSchedule')
                          this.fullscreenLoading = false
                        } else {
                          this.messageToastErr(res.data.message)
                        }
                      }
                    }
                  }
                })
                .catch((error) => {
                  console.log(error)
                  this.fullscreenLoading = false
                  this.messageToastErr('error,please try again leter')
                })
            }
          } else {
            this.messageToastErr('error submit!!')
            return false
          }
        })
      },
      // 将获取的日期格式化
      getCompletion (date) {
        let oDate = new Date(date)
        let h = oDate.getHours()
        let m = oDate.getMinutes()
        let s = oDate.getSeconds()
        if (parseInt(h) < 10) {
          h = '0' + h
        }
        let oTime = h + ':' + m + ':' + s
        return oTime
      },
      // 初始化 Bus Line 表单
      initForm () {
        this.loading = true
        initRouteSchedule(this.id).then((res) => {
          if (res.data) {
            this.submitForm.status = res.data.status
            // if (res.data.directionId) {
            //   this.submitForm.directionId = res.data.directionId
            //   this.initScheduleOne()
            // }
            this.submitForm.routeId = res.data.routeId
            this.submitForm.schedule = new Date(res.data.schedule)
            if (res.data.schedule) {
              // let cTime = this.getCompletion(res.data.schedule)
              this.submitForm.schedule = res.data.schedule
            }
            this.loading = false
          }
        }).catch((error) => {
          if (error.response) {
            // 请求已经发出，但是服务器响应返回的状态吗不在2xx的范围内
            console.log(error.response.data)
            console.log(error.response.status)
            console.log(error.response.header)
          } else {
            // 一些错误是在设置请求的时候触发
            console.log('Error', error.message)
          }
          console.log(error.config)
          this.loading = false
          this.messageToastErr('error,please refresh the page later')
        })
      },
      // onTrainDirection() {
      //   onTrainDirectionQueryJson().then((res) => {
      //     let data = res.data;
      //
      //     // 下拉菜单数据装载
      //
      //     this.directionNameEns = [];
      //
      //     for (let i = 0; i < data.length; i++) {
      //       this.directionNameEns.push({
      //         value: data[i].id,
      //         text: data[i].nameEn
      //       })
      //     }
      //
      //   }).catch((e) => {
      //     console.log(e)
      //   })
      // },
      initSchedule() {

        initRouteScheduleList({directionId: this.submitForm.directionId}).then((res) => {
          if (res.data) {
            let data = res.data;

            // 下拉菜单数据装载

            this.routes = [];
            // this.submitForm.routeId = null;
            for (let i = 0; i < data.length; i++) {
              this.routes.push({
                value: data[i].id,
                text: data[i].nameEn
              })
            }
          }
        }).catch((error) => {
          if (error.response) {
            // 请求已经发出，但是服务器响应返回的状态吗不在2xx的范围内
            console.log(error.response)
          } else {
            // 一些错误是在设置请求的时候触发
            console.log('Error', error.message)
          }
          console.log(error.config)
          this.messageToastErr('error,please refresh the page later')
        })
      },
      initScheduleOne() {

        initRouteScheduleList({directionId: this.submitForm.directionId}).then((res) => {
          if (res.data) {
            let data = res.data;

            // 下拉菜单数据装载

            this.routes = [];

            for (let i = 0; i < data.length; i++) {
              this.routes.push({
                value: data[i].id,
                text: data[i].nameEn
              })
            }
          }
        }).catch((error) => {
          if (error.response) {
            // 请求已经发出，但是服务器响应返回的状态吗不在2xx的范围内
            console.log(error.response)
          } else {
            // 一些错误是在设置请求的时候触发
            console.log('Error', error.message)
          }
          console.log(error.config)
          this.messageToastErr('error,please refresh the page later')
        })
      }
    },
    mounted () {
      // this.onTrainDirection()
      this.initSchedule()
      this.id = this.$route.query.id || ''
      if (this.id) {
        this.initForm()
      }
    }
  }
</script>
<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }
  .food-content-box .container-padding {
    padding: 20px 40px 0 40px;
  }
  .list-notes{
    text-align: center;
    display: block;
  }
</style>
